<?php
require_once 'Zend/Loader.php';

class BootstrapConsole extends Zend_Application_Bootstrap_Bootstrap
{

    
   	protected function _initLogger()
    {
        $logger = new Zend_Log();
		//$writer = new Zend_Log_Writer_Stream('php://output');
		$writer = new Zend_Log_Writer_Stream('/tmp/concentre-daemon.log');
		
		$filter = new Zend_Log_Filter_Priority(Zend_Log::INFO);
		$logger->addFilter($filter);

		$logger->addWriter($writer);
		
		
        Zend_Registry::set('logger', $logger);


    }

    public function run() {

	require_once 'Zend/Console/Getopt.php';
	try {
        	$opts = new Zend_Console_Getopt(
                	array(
				'help|h'	=> 'Displays usage information.',
                		'module|m=s'    => 'Set module name',
                		'controller|c=s'=> 'Set controller name',
                		'action|a=s'    => 'Set action name',
                 	));
		
		$opts->parse();
	} catch (Zend_Console_Getopt_Exception $e) {
	    echo $e->getMessage() . PHP_EOL . $e->getUsageMessage();
	    return;
	}	


	if(isset($opts->h)) {
	    echo $opts->getUsageMessage();
    	    return;
	}

	$args = $opts->getRemainingArgs();
	
	switch($args[0]) {
		case 'stop':	
			$this->getResource('Daemon')->stop();
			return;
		case 'start':
			$this->getResource('Daemon')->start();	
			break;
		default:
			echo $opts->getUsageMessage();
		        return;
	}
			

  	$front   = $this->getResource('FrontController');
        $default = $front->getDefaultModule();
        
        if (null === $front->getControllerDirectory($default)) {
            throw new Zend_Application_Bootstrap_Exception(
                'No default controller directory registered with front controller'
            );
        }
        
    	$front->setRequest(new Zend_Controller_Request_Simple($opts->a, $opts->c, $opts->m));
    	$front->setRouter(new Concentre_Controller_Router_Console());
 	$front->setResponse(new Zend_Controller_Response_Cli());
        $front->setParam('bootstrap', $this);
        
        
        while (true) {
	        $front->dispatch();
			sleep(1);
		}
	}
}
